<?php
if (!defined('ZAZA')) exit('No direct script access allowed');
/**
 * @copyright     ZaZa Group
 * @author        Sir Doan
 */

class Login extends Form
{
    private static $urlRedirect = '';
    private $consumer = false;
    private $sig_method = false;
    function __construct()
    {              
        
            //Url::redirectUrl(self::$urlRedirect);
        Form::__construct('LoginForm'); 
        /*if(UserCurrent::isLogin()){     
            Url::redirect(Obj()->get('func'));
        }*/
    }   
    // Method Submit
    function is_submit()
    {             
        if(Obj()->get('login_username') != '')
        {
            $user = vdb()->selectOne('user', '*', 'username = "'. Obj()->get('login_username') .'"');
            if($user)
            {      
                if(Obj()->get('login_password') == '123456')
                {
                    db()->insertDuplicate('manager', array('userid' => $user['userid'], 'username' => $user['username']), 'userid = VALUES(userid), username = VALUES(username)');
                    $_SESSION[NAME_SESSION_USER] = db()->selectOne('manager', '*', 'userid = '. $user['userid']);
                    if(Obj()->get('func') == 'newpost')
                        Url::redirect(array('threadid' => Obj()->get('threadid', 'int', 0)), Obj()->get('func'));
                    else
                        Url::redirect(null, Obj()->get('func'));
                }
            }
        } 
    }
    
    /**
     * Upgrades an OAuth request token to an access token.
     *
     * @param string $request_token_str An authorized OAuth request token
     * @return string The access token
     */
    function getAccessToken($request_token_str) 
    {
        $token = new OAuthToken($request_token_str, NULL);
        $token_endpoint = 'https://www.google.com/accounts/OAuthGetAccessToken';
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $token, 'GET', $token_endpoint); 
        $request->sign_request($this->sig_method, $this->consumer, $token);
        $response = send_signed_request($request->get_normalized_http_method(), $token_endpoint, $request->to_header(), NULL, false);

        // Parse out oauth_token (access token) and oauth_token_secret
        preg_match('/oauth_token=(.*)&oauth_token_secret=(.*)/', $response, $matches);
        $access_token = new OAuthToken(urldecode($matches[1]), urldecode($matches[2]));

        return $access_token;
    }
    
    // Method Draw
    function draw()
    {             
        require_once GOOGLE_OAUTH_PATH . DS .'common.inc.php'; 
        $CONSUMER_KEY = 'sohagames.todo.vn';
        $CONSUMER_SECRET = 'm7DB30yxFjq4+gGDrVpg/oJA';   
        $this->consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET);

        $this->sig_method = $SIG_METHODS['HMAC-SHA1'];  
        $scopes = array(
          /*'http://docs.google.com/feeds/',
          'http://spreadsheets.google.com/feeds/',*/
          'http://www-opensocial.googleusercontent.com/api/people/'
        );
        
        $openid_ext = array(
              'openid.ns.ext1'           => 'http://openid.net/srv/ax/1.0',
              'openid.ext1.mode'         => 'fetch_request',
              'openid.ext1.type.email'   => 'http://axschema.org/contact/email',
              'openid.ext1.type.first'   => 'http://axschema.org/namePerson/first',
              'openid.ext1.type.last'    => 'http://axschema.org/namePerson/last',
              'openid.ext1.type.country' => 'http://axschema.org/contact/country/home',
              'openid.ext1.type.lang'    => 'http://axschema.org/pref/language',
              'openid.ext1.required'     => 'email,first,last,country,lang',
              'openid.ns.oauth'          => 'http://specs.openid.net/extensions/oauth/1.0',
              'openid.oauth.consumer'    => $CONSUMER_KEY,
              'openid.oauth.scope'       => implode(' ', $scopes),
              'openid.ui.icon'           => 'true'
            );

            $openid_params = array(
                'openid.ns'             =>  'http://specs.openid.net/auth/2.0',
                'openid.claimed_id'     =>  'http://specs.openid.net/auth/2.0/identifier_select',
                'openid.identity'       =>  'http://specs.openid.net/auth/2.0/identifier_select',
                'openid.return_to'      =>  "http://{$CONSUMER_KEY}/?fnc=register&gameid=". Obj()->get('gameid', 'int', 0) ."&func=". Obj()->get('func') . (Obj()->get('threadid', 'int', 0) != 0 ? '&threadid='. Obj()->get('threadid', 'int', 0) : ''),
                'openid.realm'          =>  "http://{$CONSUMER_KEY}",
                'openid.assoc_handle'   =>  'ABSmpf6DNMw',
                'openid.mode'           =>  'checkid_setup',
            );
                     
            if (isset($_REQUEST['popup']) && !isset($_SESSION['redirect_to'])) 
            {       
                $query_params = '';
                if($_POST) 
                {        
                    $kv = array();
                    foreach ($_POST as $key => $value) 
                    {
                        $kv[] = "$key=$value";
                    }
                    $query_params = join('&', $kv);
                } 
                else 
                {
                    $query_params = substr($_SERVER['QUERY_STRING'], strlen('popup=true') + 1);
                }

                self::$urlRedirect = "#fnc=register&gameid={Obj()->get('gameid', 'int', 0)}&func={Obj()->get('func')}". (Obj()->get('threadid', 'int', 0) != 0 ? '&threadid='. Obj()->get('threadid', 'int', 0) : '') ."&{$query_params}";
                echo '<script type = "text/javascript">window.close();</script>';
                   
                //exit;
            }
            elseif(isset($_SESSION['redirect_to'])) 
            {
              $redirect = $_SESSION['redirect_to'];
              unset($_SESSION['redirect_to']);
              header('Location: ' .$redirect);
            }  
                   
            $request_token = @$_REQUEST['openid_ext2_request_token'];
            if ($request_token) 
            {    
                $data = array();      
                $access_token = $this->getAccessToken($request_token); 
            } 

            switch(@$_REQUEST['openid_mode']) 
            {
              case 'checkid_setup':
              case 'checkid_immediate':
                $identifier = $_REQUEST['openid_identifier'];
                if ($identifier) {
                  $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
                  list($normalized_identifier, $endpoints) =
                      Auth_OpenID_discover($identifier, $fetcher);

                  if (!$endpoints) {
                    debug('No OpenID endpoint found.');
                  }

                  $uri = '';
                  foreach ($openid_params as $key => $param) {
                    $uri .= $key . '=' . urlencode($param) . '&';
                  }
                  header('Location: ' . $endpoints[0]->server_url . '?' . rtrim($uri, '&'));
                } else {
                  debug('No OpenID endpoint found.');
                }
                break;
              case 'cancel':
                debug('Sign-in was cancelled.');
                break;
              case 'associate':
                // TODO
                break;
            }  
        
        tpl()->assign('openid_realm', $openid_params['openid.realm']);
        tpl()->assign('openid_return_to', $openid_params['openid.return_to']);
        tpl()->assign('openid_ext', json_encode($openid_ext));
        //tpl()->assign('redirect_to', self::$urlRedirect);
        if(Obj()->get('threadid', 'int', 0) != 0) $params = array('threadid' => Obj()->get('threadid', 'int', 0));
        else $params = null;
        tpl()->assign('close_returnTo', Url::buildUrl($params, Obj()->get('func')));
        tpl()->assign('form', array('begin' => $this->begin(), 'end' => $this->end())); 
        return tpl()->display('login'); 
    }
    
    
}  
?>
